/**
 * 
 */
package com.vision.sales.sv.serv;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vision.core.cm.data.ApplicationId;
import com.vision.core.cm.db.data.Permission;
import com.vision.core.cm.db.data.Role;
import com.vision.core.sv.db.CustomSessionFactoryBean;
import com.vision.core.sv.db.mgr.ISimpleCriteria;
import com.vision.core.sv.db.mgr.PermissionManager;
import com.vision.core.sv.db.mgr.RoleManager;
import com.vision.core.sv.db.mgr.SimpleCriteria;
import com.vision.core.sv.serv.DatabaseInitializerServlet;
import com.vision.sales.cm.data.SalesPermissions;
import com.vision.sales.cm.db.data.SalesmanProduct;

/**
 * TODO For local deployments, we might have to remove this for security reasons.
 * FIXME 0 This can run only after {@link DatabaseInitializerServlet} has ran.
 * 
 * @author Mark
 *
 */
public class SalesInitializerServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private static final Logger log = LoggerFactory.getLogger(SalesInitializerServlet.class);
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
		try {
			if (!isDatabaseInitialized()) {
				log.info("Database is not yet initialized. Initializing database...");
				initializeDatabase();
				log.info("Database successfully initialized.");
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new ServletException("Error initializing the database.", e);
		}
	}
	
	@SuppressWarnings("unchecked")
	protected boolean isDatabaseInitialized() throws SQLException {
		SessionFactory sf = CustomSessionFactoryBean.getFactory();
		PermissionManager permissionManager = new PermissionManager();
		permissionManager.setSessionFactory(sf);
		
		// Check if the Sales-related Permissions are already in the database
		ISimpleCriteria crit = SimpleCriteria.forClass(Permission.class);
		crit.eq("applicationId", ApplicationId.Sales); // NOTE This one uses the field name in the class, not the column name in the database
		List<SalesmanProduct> list = permissionManager.getTemplate().findByCriteria(crit.getDetached());
		return !list.isEmpty();
	}
	
	protected void initializeDatabase() {
		SessionFactory sf = CustomSessionFactoryBean.getFactory();

		// Create the Sales-related Permissions
		PermissionManager permissionManager = new PermissionManager();
		permissionManager.setSessionFactory(sf);
		
		for (Permission permission : SalesPermissions.All) {
			permissionManager.create(permission);
		}
		
		// Assign the Sales-related Permissions into the appropriate Roles
		RoleManager roleManager = new RoleManager();
		roleManager.setSessionFactory(sf);
		
		Role role = roleManager.getById(Role.ROOT_NAME);
		role.addPermissions(new ArrayList<Permission>(SalesPermissions.All));
		
		roleManager.update(role);
	}

}
